package transcoding
import com.xuggle.xuggler.IContainerFormat
import play.api.Logger

class MediaFileManager(val mainMediaFile: MediaFile) {

  var otherVersions: IndexedSeq[MediaFile] = scala.collection.mutable.IndexedSeq()

  def addOtherVersion(mediaFile: MediaFile) = {
    val idx = otherVersions.indexOf(mediaFile)
    if (idx < 0) otherVersions = otherVersions :+ mediaFile
    else otherVersions = otherVersions updated (idx, mediaFile)
  }

  def getMediaFileWithMaxBitRateAndFormat(maxBitRate: Option[Int], format: Option[IContainerFormat]) = {
    if (mainMediaFile.bitRate.getOrElse(0) <= maxBitRate.getOrElse(Int.MaxValue) &&
      mainMediaFile.format.map(informat => informat.getInputFormatShortName.equals(format.getOrElse(informat).getInputFormatShortName))
      .getOrElse(false))
      Some(mainMediaFile)
    else
      otherVersions.filter(mf => mf.bitRate.getOrElse(0) <= maxBitRate.getOrElse(Int.MaxValue))
        .sortWith((m1, m2) => m1.bitRate.get >= m2.bitRate.get)
        .filter(mf => mf.format.isDefined &&
          mf.format.get.getInputFormatShortName.equals(format.getOrElse(mf.format.get).getInputFormatShortName))
        .headOption
  }

  def getMediaFileWithFormat(format: IContainerFormat) = {
    getMediaFileWithMaxBitRateAndFormat(None, Some(format))
  }

  def getMediaFileWithMaxBitRate(maxBitRate: Int) = {
    getMediaFileWithMaxBitRateAndFormat(Some(maxBitRate), None)
  }
}

object Test {
  def getFormat(format: String) = {
    val f = IContainerFormat.make()
    f.setInputFormat(format)

    f
  }
  def _1 = {
    val main = MediaFile("/home/giacomo/Videos/127.Hours.2010.DVDSCR.AC3.XViD-T0XiC-iNK/127.Hours.2010.DVDSCR.AC3.XViD-T0XiC-iNK.avi")
    val manager = new MediaFileManager(main)
    val f = IContainerFormat.make()
    f.setInputFormat("flv")

    Logger.error(manager.getMediaFileWithMaxBitRateAndFormat(main.bitRate, Some(f)).toString)

    val otherV = MediaFile("/home/giacomo/Videos/127.Hours.2010.DVDSCR.AC3.XViD-T0XiC-iNK/sample.avi.flv")
    manager.addOtherVersion(otherV)
    Logger.error(manager.getMediaFileWithMaxBitRateAndFormat(None, Some(f)).toString)

    manager
  }
}